package com.df.controller;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/process")
@Slf4j
public class ProcessController {
    
    @Autowired
    private RuntimeService runtimeService;
    
    /**
     * 启动外部任务流程
     */
    @GetMapping("/start")
    public Map<String, Object> startExternalTaskProcess(@RequestBody(required = false) Map<String, Object> variables) {
        try {
            log.info("开始启动外部任务流程");
            
            // 如果没有传入变量，使用默认变量
            if (variables == null) {
                variables = new HashMap<>();
            }
            
            // 添加一些默认变量
            variables.put("startTime", System.currentTimeMillis());
            variables.put("processType", "EXTERNAL_TASK");
            
            // 启动流程实例
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ExternalTaskProcess", variables);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("processInstanceId", processInstance.getId());
            result.put("processDefinitionId", processInstance.getProcessDefinitionId());
            result.put("message", "外部任务流程启动成功");
            
            log.info("外部任务流程启动成功，流程实例ID: {}", processInstance.getId());
            
            return result;
            
        } catch (Exception e) {
            log.error("启动外部任务流程失败", e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("message", "外部任务流程启动失败");
            
            return result;
        }
    }
    
    /**
     * 获取流程实例状态
     */
    @GetMapping("/status/{processInstanceId}")
    public Map<String, Object> getProcessStatus(@PathVariable String processInstanceId) {
        try {
            log.info("查询流程实例状态，流程实例ID: {}", processInstanceId);

            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
            
            Map<String, Object> result = new HashMap<>();

            result.put("success", true);
            result.put("processInstanceId", processInstanceId);
            if (processInstance != null) {
                result.put("status", "RUNNING");
                result.put("processDefinitionId", processInstance.getProcessDefinitionId());
                result.put("businessKey", processInstance.getBusinessKey());
                
                // 获取流程变量
                Map<String,Object> variables = runtimeService.getVariables(processInstanceId);
                result.put("variables", variables);
                
            } else {
                result.put("status", "COMPLETED");
                result.put("message", "流程实例已完成");
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("查询流程实例状态失败，流程实例ID: {}", processInstanceId, e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("message", "查询流程实例状态失败");
            
            return result;
        }
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("service", "Camunda External Task Server");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
} 